#define _CRT_SECURE_NO_WARNINGS
#include"list.h"
LST* BuyLTNode(LTDataType x)
{
	LST* newnode = (LST*)malloc(sizeof(LST));
	if (newnode == NULL)
	{
		perror("malloc failed");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

void ListDestory(LST* phead)
{
	assert(phead);
	LST* cur = phead->next;
	while (cur != phead)
	{
		LST* del = cur->next;
		free(cur);
		cur = del;
	}
	free(phead);
}

void ListPrint(LST* phead)
{
	assert(phead);
	printf("phead<=>");
	LST* cur = phead->next;
	while (cur!=phead)
	{
		printf("%d<->", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void ListPushBack(LST* phead, LTDataType x)
{
	assert(phead);
	LST* tail = phead->prev;
	
	LST* newnode = BuyLTNode(x);
	tail->next = newnode;
	newnode->prev = tail;
	phead->prev = newnode;
	newnode->next = phead;
}

void ListPopBack(LST* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LST* tail = phead->prev;
	LST* tailprev = tail->prev;
	free(tail);
	phead->prev = tailprev;
	tailprev->next = phead;
}

void ListPushFront(LST* phead, LTDataType x)
{
	assert(phead);
	LST* newnode = BuyLTNode(x);
	LST*tail=phead->next;
	phead->next = newnode;
	newnode->next = tail;
	newnode->prev = phead;
	tail->prev = newnode;
}

void ListPopFront(LST* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LST* tail = phead->next;
	LST* cur = tail->next;
	phead->next = cur;
	cur->prev = phead;
	free(tail);
}

LST* ListFind(LST* phead, LTDataType x)
{
	assert(phead);
	LST* cur = phead->next;
	while (cur!=phead)
	{
		if (cur->data== x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(LST* pos, LTDataType x)
{
	assert(pos);
	LST* newnode = BuyLTNode(x);
	LST* posprev = pos->prev;
	posprev->next = newnode;
	newnode->prev = posprev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(LST* pos)
{
	assert(pos);
	LST* posprev = pos->prev;
	LST* posnext = pos->next;
	posprev->next = posnext;
	posnext->prev = posprev;
	free(pos);
}